package core

import (
	"context"
	"fmt"
	"log"
	"net"
	"net/http"
	"os"
	"os/signal"
	"time"

	"gitee.com/hwpro/cvecompetition/global"
	"gitee.com/hwpro/cvecompetition/sysinit"
)

func RunServer(port int) {
	initLog()
	router := sysinit.InitRouter()
	//start server
	s := &http.Server{
		Addr:           fmt.Sprintf(":%d", port),
		Handler:        router,
		ReadTimeout:    20 * time.Second,
		WriteTimeout:   20 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}
	sAddress := fmt.Sprintf("%s:%d ", getClientIp(), global.FlagOption.Port)
	global.GmsLog.Debug("server run success on", sAddress)
	fmt.Printf(`欢迎使用 gauss-competition-server api
	default api address :http://%s/swagger/index.html
	request api address :http://%s`, sAddress, sAddress)
	go func() {
		if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			global.GmsLog.Error("sever start fail", err)
			log.Fatalf("listen: %s\n", err)
		}
	}()
	quit := make(chan os.Signal)
	signal.Notify(quit, os.Interrupt)
	<-quit
	global.GmsLog.Error("shutdown server ...")
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()
	if err := s.Shutdown(ctx); err != nil {
		global.GmsLog.Error("sever shutdown:", err)
		log.Fatalf("sever shutdown: %s\n", err)
	}
	global.GmsLog.Debug("sever exiting")
}

func getClientIp() string {
	addrs, err := net.InterfaceAddrs()
	if err != nil {
		return "127.0.0.1"
	}
	for _, address := range addrs {
		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
			if ipnet.IP.To4() != nil {
				return ipnet.IP.String()
			}

		}
	}
	return "127.0.01"
}
